package vn.com.hung.notetaker.mis.menus;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import vn.com.hung.notetaker.mis.forms.MiscForm;
import vn.com.hung.notetaker.utils.XMLFilter;

public class MisMenu extends JMenuBar implements ActionListener{
    
    private MiscForm mainForm;
    private JMenu file = new JMenu("File");
    private JMenuItem loadItem = new JMenuItem("Load", KeyEvent.VK_L);
    private JMenuItem saveAsItem = new JMenuItem("Save As", KeyEvent.VK_S);
    
    public MisMenu(MiscForm form) {
        this.mainForm = form;
        initComponents();
        add(file);
        
    }

    private void initComponents() {
        file.add(loadItem);
        file.add(saveAsItem);
        loadItem.addActionListener(this);
        saveAsItem.addActionListener(this);
        
        
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        JMenuItem item = (JMenuItem) arg0.getSource();
        if (item.equals(loadItem)) {
            JFileChooser c = new JFileChooser();
            c.setFileFilter(new XMLFilter());
            int returnValue = c.showOpenDialog(getParent());
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File selectedFile = c.getSelectedFile();
                mainForm.load(selectedFile);
            }
        } else if (item.equals(saveAsItem)) {
            JFileChooser c = new JFileChooser();
            c.setFileFilter(new XMLFilter());
            int returnValue = c.showSaveDialog(getParent());
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                String fileName = c.getSelectedFile().getPath();
                if (!fileName.endsWith(".xml")) {
                    fileName += ".xml";
                }
                mainForm.saveXML(fileName);
            }
        }
    }
    

}
